import json, urllib, urllib2

BING_API_KEY = "87bfKsr8Glb5qAlnrjv7rRy6VkchVDW5vHnXyoW7Dm4"
ROOT_URL = 'https://api.datamarket.azure.com/Bing/Search/'
SOURCE = 'Web'
RESULT_PER_PAGE = 10
OFFSET = 0

def get_back_link(request):
    try:
        return request.META['HTTP_REFERER'][len('http://'+ request.META['HTTP_HOST']):]
    except KeyError:
        return ""
    
def run_query(search_terms):
    query = "'{0}'".format(search_terms)
    query = urllib.quote(query)
    
    search_url = "{0}{1}?$format=json&$top={2}&$skip={3}&Query={4}".format(
        ROOT_URL,
        SOURCE,
        RESULT_PER_PAGE,
        OFFSET,
        query)
        
    username = ''
    
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_mgr.add_password(None, search_url, username, BING_API_KEY)
    
    results = []
    try:
        handler = urllib2.HTTPBasicAuthHandler(password_mgr)
        opener = urllib2.build_opener(handler)
        urllib2.install_opener(opener)
        
        response = urllib2.urlopen(search_url).read()
        
        json_result = json.loads(response)
        
        for result in json_result['d']['results']:
            results.append({'title': result['Title'],
                'link': result['Url'],
                'summary': result['Description']})
    except urllib2.URLError, e:
        print "Error when quering the Bing API", e
        
    return results